<template>
	<view class="collection-container">
		<!-- 页面标题（复用定制页风格） -->
		<view class="page-title">我的汉服定制</view>

		<!-- 记录列表区域 -->
		<view class="record-list">
			<!-- 加载中状态 -->
			<view class="loading" v-if="isLoading">
				<uni-loading-icon size="24" color="#8b5a2b"></uni-loading-icon>
				<view class="loading-text">加载定制记录中...</view>
			</view>

			<!-- 无数据状态 -->
			<view class="empty" v-else-if="records.length === 0">
				<image src="/static/empty-hanfu.png" mode="widthFix" class="empty-img"></image>
				<view class="empty-text">暂无汉服定制记录</view>
				<view class="to-customize-btn" @click="goto3dPage">
				    去定制汉服
				</view>
			</view>

			<!-- 定制记录卡片（循环渲染） -->
			<view class="record-card" v-for="record in records" :key="record.id">
				<!-- 卡片头部：ID+时间 -->
				<view class="card-header">
					<view class="record-id">定制ID：{{ record.id }}</view>
					<view class="record-time">{{ formatTime(record.createdAt) }}</view>
				</view>

				<!-- 卡片内容：定制信息 -->
				<view class="card-content">
					<!-- 颜色预览区（直观展示） -->
					<view class="color-preview">
						<view class="color-item">
							<view class="color-dot" :style="{ backgroundColor: record.color }"></view>
							<view class="color-name">主色：{{ record.colorName }}</view>
						</view>
						<view class="color-item">
							<view class="color-dot" :style="{ backgroundColor: record.color1 }"></view>
							<view class="color-name">副色：{{ record.color1Name }}</view>
						</view>
						<view class="color-item">
							<view class="color-dot" :style="{ backgroundColor: record.color2 }"></view>
							<view class="color-name">辅助色：{{ record.color2Name }}</view>
						</view>
					</view>

					<!-- 核心信息区 -->
					<view class="info-list">
						<view class="info-item">
							<view class="info-label">样式</view>
							<view class="info-value">{{ record.styleName }}</view>
						</view>
						<view class="info-item">
							<view class="info-label">花纹</view>
							<view class="info-value">{{ record.patternName || '未选择' }}</view>
						</view>
						<view class="info-item">
							<view class="info-label">图案</view>
							<view class="info-value">{{ record.designName || '未选择' }}</view>
						</view>
						<view class="info-item">
							<view class="info-label">布料</view>
							<view class="info-value">{{ record.fabricName || '未选择' }}</view>
						</view>
					</view>
				</view>

				<!-- 卡片底部：操作按钮 -->
				<view class="card-footer">
					<!-- 跳转3D预览按钮 -->
					<button class="preview-btn" @click="goto3DPreview(record)">
						3D预览
					</button>
					<!-- 删除按钮 -->
					<button class="delete-btn" @click="confirmDelete(record.id)">
						删除
					</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				records: [], // 存储获取到的定制记录
				isLoading: true, // 加载状态
				userId: null
			};
		},
		// 页面加载时自动获取数据
		onLoad() {
			try {
			        const storedInfo = uni.getStorageSync('userInfo');
			        
			        if (storedInfo && storedInfo.id) {
			          this.userId = storedInfo.id;
					  this.getHanfuRecords();
			        } else {
			          console.log('用户未登录或信息不完整');
			          // 可以跳转到登录页
			          // uni.redirectTo({ url: '/pages/login/login' });
			        }
			      } catch (error) {
			        console.error('读取用户数据失败:', error);
			      }
			
		},
		methods: {
			// 1. 从后端获取用户的定制记录
			async getHanfuRecords() {
				try {
					// 调用后端查询接口（参数：userId）
					const res = await uni.$http.get(`/hanfu/records?userId=${this.userId}`);

					// 处理响应（适配你后端的返回格式：code=1 表示成功）
					if (res.statusCode === 200 && res.data.code === 1) {
						this.records = res.data.data; // 赋值记录列表
					} else {
						uni.showToast({
							title: res.data.msg || '获取记录失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('获取记录出错：', error);
					uni.showToast({
						title: '网络错误，请稍后重试',
						icon: 'none'
					});
				} finally {
					this.isLoading = false; // 结束加载状态
				}
			},

			// 2. 格式化时间（如：2025-08-25 14:30:20）
			formatTime(timeStr) {
				if (!timeStr) return '';
				const date = new Date(timeStr);
				// 补零函数（确保月份/日期/时分秒是两位数）
				const padZero = num => num < 10 ? `0${num}` : num;
				return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())} ${padZero(date.getHours())}:${padZero(date.getMinutes())}:${padZero(date.getSeconds())}`;
			},

			// 3. 跳转3D预览页面（携带当前记录的所有定制参数）
			goto3DPreview(record) {
				// 将记录参数转为URL参数（适配3D页面接收）
				const queryParams = JSON.stringify({
					color: record.color,
					color_1: record.color1, // 注意：3D页面用color_1，这里要转下划线
					color_2: record.color2,
					colorName: record.colorName,
					color_1Name: record.color1Name,
					color_2Name: record.color2Name,
					style: record.style,
					styleName: record.styleName,
					pattern: record.pattern,
					patternName: record.patternName,
					design: record.design,
					designName: record.designName,
					fabric: record.fabric,
					fabricName: record.fabricName
				});

				// 存入本地存储（避免URL参数过长）
				uni.setStorageSync('hanfuCustomParams', queryParams);
				console.log("要存：",queryParams);
				//  跳转到3D页面（无需携带长参数）
				uni.switchTab({
					url: '/pages/3d/3d' // 你的3D页面路径正确
				});
			},

			// 4. 删除记录
			confirmDelete(recordId) {
			    // 1. 获取当前登录用户ID
			    // const userId = uni.getStorageSync('userId'); // 从本地存储获取用户ID
				const userId=this.userId;
			    if (!userId) {
			        uni.showToast({
			            title: '请先登录',
			            icon: 'none'
			        });
			        return;
			    }
			
			    // 2. 弹窗确认
			    uni.showModal({
			        title: '确认删除',
			        content: '删除后该定制记录将不可恢复，是否继续？',
			        confirmColor: '#8b5a2b', // 与整体风格一致的棕色
			        cancelColor: '#999',
					success: async (res) => { // 注意这里要加 async，因为内部要调用 await
					            console.log("用户点击结果：", res.confirm);
					            if (res.confirm) {
					                // 这里的逻辑和之前一致
					                try {
					                    const res = await uni.$http.delete(`/hanfu/delete?userId=${userId}&recordId=${recordId}`);
					                    if (res.data.code === 1) {
					                        uni.showToast({ title: '删除成功', icon: 'success' });
					                        this.getHanfuRecords();
					                    } else {
					                        uni.showToast({ title: res.data.msg || '删除失败', icon: 'none' });
					                    }
					                } catch (error) {
					                    console.error('删除记录出错：', error);
					                    uni.showToast({ title: '网络错误，请稍后重试', icon: 'none' });
					                }
					            }
					        }
			    });
			},
			goto3dPage() {
			      uni.switchTab({
			        url: '/pages/3d/3d' 
			      });
			    }
	}
	};
</script>

<style scoped>
	/* 页面容器*/
	.collection-container {
		min-height: 100vh;
		background-color: #f8f5f0;
		padding-bottom: 40rpx;
	}

	/* 页面标题 */
	.page-title {
		padding: 20rpx 0;
		text-align: center;
		font-size: 36rpx;
		font-weight: bold;
		background-color: #8b5a2b;
		color: #f5f0e6;
		border-bottom: 1px solid #a67c52;
	}

	/* 记录列表容器 */
	.record-list {
		padding: 20rpx 15rpx;
	}

	/* 加载中样式 */
	.loading {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-top: 120rpx;
		gap: 15rpx;
	}

	.loading-text {
		font-size: 24rpx;
		color: #5c3d1f;
	}

	/* 无数据样式 */
	.empty {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-top: 100rpx;
		gap: 25rpx;
	}

	.empty-img {
		width: 220rpx;
		height: 220rpx;
		opacity: 0.6;
	}

	.empty-text {
		font-size: 26rpx;
		color: #999;
	}

	.to-customize-btn {
		padding: 15rpx 35rpx;
		background-color: #8b5a2b;
		color: #f5f0e6;
		font-size: 24rpx;
		border-radius: 30rpx;
	}

	/* 记录卡片：古风卡片风格 */
	.record-card {
		background-color: #f5f0e6;
		border-radius: 15rpx;
		box-shadow: 0 2rpx 12rpx rgba(139, 90, 43, 0.1);
		padding: 25rpx;
		margin-bottom: 20rpx;
	}

	/* 卡片头部：ID和时间 */
	.card-header {
		display: flex;
		justify-content: space-between;
		margin-bottom: 20rpx;
		padding-bottom: 15rpx;
		border-bottom: 1px solid #d9c9b8;
	}

	.record-id {
		font-size: 24rpx;
		color: #5c3d1f;
		font-weight: 500;
	}

	.record-time {
		font-size: 20rpx;
		color: #7d5a36;
	}

	/* 卡片内容：颜色预览区 */
	.color-preview {
		display: flex;
		justify-content: space-between;
		margin-bottom: 25rpx;
		padding: 0 10rpx;
	}

	.color-item {
		display: flex;
		align-items: center;
		gap: 12rpx;
	}

	.color-dot {
		width: 24rpx;
		height: 24rpx;
		border-radius: 50%;
		border: 1px solid #d9c9b8;
	}

	.color-name {
		font-size: 22rpx;
		color: #5c3d1f;
	}

	/* 卡片内容：信息列表 */
	.info-list {
		display: flex;
		flex-direction: column;
		gap: 18rpx;
	}

	.info-item {
		display: flex;
		padding: 5rpx 0;
		border-bottom: 1px dashed #eee;
	}

	.info-label {
		width: 120rpx;
		font-size: 22rpx;
		color: #7d5a36;
	}

	.info-value {
		flex: 1;
		font-size: 22rpx;
		color: #5c3d1f;
		word-break: break-all;
		/* 处理长文本（如URL）换行 */
	}

	/* 卡片底部：操作按钮 */
	.card-footer {
		display: flex;
		justify-content: flex-end;
		gap: 15rpx;
		margin-top: 25rpx;
	}

	.preview-btn {
		padding: 10rpx 25rpx;
		background-color: #8b5a2b;
		color: #f5f0e6;
		font-size: 24rpx;
		border-radius: 8rpx;
	}

	.delete-btn {
		padding: 10rpx 25rpx;
		background-color: #fff;
		color: #8b5a2b;
		border: 1px solid #8b5a2b;
		font-size: 24rpx;
		border-radius: 8rpx;
	}
</style>
